package tako.wisers.com.android.apis.http;

import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.io.IOUtils;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpParams;

public class HttpGeter {
	private HttpResponse mResponse;
	private HttpEntity mEntity;
	
	public HttpGeter(String url){
		try {
			HttpGet mGeter = new HttpGet(url);
			mGeter.getParams().setParameter("http.socket.timeout", new Integer(10000));
			HttpClient client = new DefaultHttpClient();
			client.getParams().setParameter("http.socket.timeout", new Integer(10000));

			mResponse = client.execute(mGeter);
			mEntity = mResponse.getEntity();
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public String getContent(){
		InputStream is = null;
		try {
			is = getInputStream();
			return IOUtils.toString(is, "UTF-8");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			if(is != null){
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return null;
	}
	
	public String getHeader(String key){
		if(mResponse == null) return null;
		Header header = mResponse.getFirstHeader(key);
		String value = header != null ? header.getValue() : null;
		return value;
	}
	
	public InputStream getInputStream(){
		try {
			return mEntity.getContent();
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
	
}
